import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../base/Constant.dart';
// import 'package:pleasant/base/SignType.dart';
import '../../entity/user_receipt_entity.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/LoadingUtil.dart';
import '../../util/SignUtil.dart';
import 'package:xlive_switch/xlive_switch.dart';

class AddInvoicePage extends StatefulWidget {
  UserReceiptListDataData item;
  AddInvoicePage({Key key, this.item}) : super(key: key);

  @override
  _AddInvoicePageState createState() => _AddInvoicePageState();
}

class _AddInvoicePageState extends State<AddInvoicePage> {
  String invoiceType = "1", companyType = "1";
  String token = "",
      purchaser = "",
      taxpayer_id = "",
      bank = "",
      is_default = "N",
      account = "",
      contact = "",
      address = "",
      linkman = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.item != null) {
      purchaser = widget.item.purchaser;
      taxpayer_id = widget.item.taxpayer_id;
      bank = widget.item.bank;
      is_default = widget.item.is_default;
      account = widget.item.account;
      contact = widget.item.contact;
      address = widget.item.address;
      linkman = widget.item.linkman;
      companyType = widget.item.type == "1" ? "2" : "1";
    }
    getString(TOKEN).then((value) {
      token = value;
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          widget.item == null ? '添加抬头' : '编辑抬头',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        elevation: 0.5,
        backgroundColor: white,
        iconTheme: new IconThemeData(color: black_99),
        brightness: Brightness.light,
        actions: <Widget>[
          widget.item != null
              ? GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
                    child: Text(
                      '删除',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black54),
                    ),
                  ),
                  onTap: () {
                    del();
                  },
                )
              : Center()
        ],
      ),
      body: new SingleChildScrollView(
          child: Container(
              height: MediaQuery.of(context).size.height,
              child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    // Container(
                    //   padding: EdgeInsets.fromLTRB(
                    //       ScreenUtil.getInstance().setHeight(DP_20),
                    //       ScreenUtil.getInstance().setHeight(DP_10),
                    //       ScreenUtil.getInstance().setHeight(DP_20),
                    //       ScreenUtil.getInstance().setHeight(DP_10)),
                    //   color: white,
                    //   child: new GestureDetector(
                    //     behavior: HitTestBehavior.opaque,
                    //     onTap: () {},
                    //     child: new Row(
                    //       children: <Widget>[
                    //         Expanded(
                    //           child: Padding(
                    //             padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                    //             child: Text("发票类型",
                    //                 style: TextStyle(
                    //                   color: black,
                    //                   fontSize: ScreenUtil.getInstance()
                    //                       .setSp(NORMAL_FONT_SIZE - 2),
                    //                 )),
                    //           ),
                    //         ),
                    //         CircularCheckBox(
                    //             value: invoiceType == "1",
                    //             activeColor: mainColor,
                    //             inactiveColor: black_99,
                    //             materialTapTargetSize:
                    //                 MaterialTapTargetSize.shrinkWrap,
                    //             onChanged: (bool x) {
                    //               invoiceType = "1";
                    //               setState(() {});
                    //             }),
                    //         Text("普通发票",
                    //             style: TextStyle(
                    //               color: Colors.black87,
                    //               fontSize: ScreenUtil.getInstance()
                    //                   .setSp(SMALL_FONT_SIZE),
                    //             )),
                    //         CircularCheckBox(
                    //             value: invoiceType == "2",
                    //             activeColor: mainColor,
                    //             inactiveColor: black_99,
                    //             materialTapTargetSize:
                    //                 MaterialTapTargetSize.shrinkWrap,
                    //             onChanged: (bool x) {
                    //               invoiceType = "2";

                    //               setState(() {});
                    //             }),
                    //         Text("增值税发票",
                    //             style: TextStyle(
                    //               color: Colors.black87,
                    //               fontSize: ScreenUtil.getInstance()
                    //                   .setSp(SMALL_FONT_SIZE),
                    //             ))
                    //       ],
                    //     ),
                    //   ),
                    // ),
                    Container(
                      // margin: EdgeInsets.only(top: 1),
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          ScreenUtil.getInstance().setHeight(DP_10),
                          ScreenUtil.getInstance().setHeight(DP_20),
                          ScreenUtil.getInstance().setHeight(DP_10)),
                      color: white,
                      child: new GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {},
                        child: new Row(
                          children: <Widget>[
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                child: Text("抬头类型",
                                    style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE - 2),
                                    )),
                              ),
                            ),
                            Checkbox(
                                value: companyType == "1",
                                activeColor: mainColor,
                                checkColor: black_99,
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                                onChanged: (bool x) {
                                  companyType = "1";
                                  setState(() {});
                                }),
                            Text("个人或事业单位",
                                style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                )),
                            Checkbox(
                                value: companyType == "2",
                                activeColor: mainColor,
                                checkColor: black_99,
                                materialTapTargetSize:
                                    MaterialTapTargetSize.shrinkWrap,
                                onChanged: (bool x) {
                                  companyType = "2";
                                  setState(() {});
                                }),
                            Text("企业",
                                style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                ))
                          ],
                        ),
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.only(top: 1, bottom: 1),
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              '抬头名称',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                            ),
                            flex: 1,
                          ),
                          Expanded(
                            child: TextField(
                              keyboardAppearance: Brightness.light,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                              maxLines: 1,
                              onChanged: (value) {
                                purchaser = value;
                              },
                              controller:
                                  TextEditingController(text: purchaser),
                              minLines: 1,
                              cursorColor: mainColor,
                              // keyboardType: TextInputType.numberWithOptions(),
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "请输入名称",
                                  border: InputBorder.none),
                            ),
                            flex: 2,
                          ),
                        ],
                      ),
                    ),
                    Offstage(
                      offstage: companyType == "1",
                      child: Container(
                          width: double.infinity,
                          color: white,
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_15)),
                          child: new Column(
                            children: <Widget>[
                              Container(
                                padding: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                decoration: BoxDecoration(
                                    color: f0Color,
                                    borderRadius: BorderRadius.circular(50)),
                                child: TextField(
                                  keyboardAppearance: Brightness.light,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(SMALL_FONT_SIZE),
                                      color: black_99),
                                  maxLines: 1,
                                  onChanged: (value) {
                                    taxpayer_id = value;
                                  },
                                  controller:
                                      TextEditingController(text: taxpayer_id),
                                  minLines: 1,
                                  cursorColor: mainColor,
                                  // keyboardType:
                                  //     TextInputType.numberWithOptions(),
                                  decoration: new InputDecoration(
                                      contentPadding: EdgeInsets.all(5),
                                      hintText: "企业纳税识别码",
                                      border: InputBorder.none),
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                decoration: BoxDecoration(
                                    color: f0Color,
                                    borderRadius: BorderRadius.circular(50)),
                                child: TextField(
                                  keyboardAppearance: Brightness.light,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(SMALL_FONT_SIZE),
                                      color: black_99),
                                  maxLines: 1,
                                  onChanged: (value) {
                                    bank = value;
                                  },
                                  controller: TextEditingController(text: bank),
                                  minLines: 1,
                                  cursorColor: mainColor,
                                  // keyboardType:
                                      // TextInputType.numberWithOptions(),
                                  decoration: new InputDecoration(
                                      contentPadding: EdgeInsets.all(5),
                                      hintText: "开户行",
                                      border: InputBorder.none),
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                margin: EdgeInsets.all(
                                    ScreenUtil.getInstance().setHeight(DP_20)),
                                decoration: BoxDecoration(
                                    color: f0Color,
                                    borderRadius: BorderRadius.circular(50)),
                                child: TextField(
                                  keyboardAppearance: Brightness.light,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(SMALL_FONT_SIZE),
                                      color: black_99),
                                  maxLines: 1,
                                  onChanged: (value) {
                                    account = value;
                                  },
                                  controller:
                                      TextEditingController(text: account),
                                  minLines: 1,
                                  cursorColor: mainColor,
                                  keyboardType:
                                      TextInputType.numberWithOptions(),
                                  decoration: new InputDecoration(
                                      contentPadding: EdgeInsets.all(5),
                                      hintText: "开户账号",
                                      border: InputBorder.none),
                                ),
                              ),
                            ],
                          )),
                    ),
                    Padding(
                      padding: EdgeInsets.all(
                          ScreenUtil.getInstance().setHeight(DP_20)),
                      child: Text("收票人信息",
                          style: TextStyle(
                            color: black,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                          )),
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              '收件人姓名',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                            ),
                            flex: 1,
                          ),
                          Expanded(
                            child: TextField(
                              keyboardAppearance: Brightness.light,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                              maxLines: 1,
                              onChanged: (value) {
                                linkman = value;
                              },
                              controller: TextEditingController(text: linkman),
                              minLines: 1,
                              cursorColor: mainColor,
                              // keyboardType: TextInputType.numberWithOptions(),
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "姓名",
                                  border: InputBorder.none),
                            ),
                            flex: 2,
                          ),
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.only(top: 1),
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              '收票人手机',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                            ),
                            flex: 1,
                          ),
                          Expanded(
                            child: TextField(
                              keyboardAppearance: Brightness.light,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                              maxLines: 1,
                              onChanged: (value) {
                                contact = value;
                              },
                              controller: TextEditingController(text: contact),
                              minLines: 1,
                              cursorColor: mainColor,
                              keyboardType: TextInputType.numberWithOptions(),
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "可用于发票服务平台查询",
                                  border: InputBorder.none),
                            ),
                            flex: 2,
                          ),
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.only(top: 1),
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_20),
                          0),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              '邮箱(必填)',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                            ),
                            flex: 1,
                          ),
                          Expanded(
                            child: TextField(
                              keyboardAppearance: Brightness.light,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black_99),
                              maxLines: 1,
                              onChanged: (value) {
                                address = value;
                              },
                              controller: TextEditingController(text: address),
                              minLines: 1,
                              cursorColor: mainColor,
                              // keyboardType: TextInputType.numberWithOptions(),
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "邮箱用于接收电子发票",
                                  border: InputBorder.none),
                            ),
                            flex: 2,
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 1),
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_20),
                          ScreenUtil.getInstance().setHeight(DP_10),
                          ScreenUtil.getInstance().setHeight(DP_20),
                          ScreenUtil.getInstance().setHeight(DP_10)),
                      color: white,
                      child: new GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {},
                        child: new Row(
                          children: <Widget>[
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                child: Text("默认发票抬头",
                                    style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE - 2),
                                    )),
                              ),
                            ),
                            XlivSwitch(
                                value: is_default == "Y",
                                unActiveColor: f0Color,
                                activeColor: mainColor,
                                onChanged: (bool x) {
                                  is_default = is_default == "N" ? "Y" : "N";
                                  setState(() {});
                                })
                          ],
                        ),
                      ),
                    ),
                    new Container(
                      width: double.infinity,
                      height: 40,
                      margin: EdgeInsets.fromLTRB(50, 30, 50, 0),
                      decoration: new BoxDecoration(
                        color:mainColor,
                          borderRadius: BorderRadius.circular(2.0)),
                      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                      child: new FlatButton(
                        child: new Padding(
                          padding: EdgeInsets.all(0.0),
                          child: new Text(
                            "保存信息",
                            style: new TextStyle(
                                color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                          ),
                        ),
                        onPressed: () {
                          if (contact == "" ||
                              address == "" ||
                              linkman == "" ||
                              purchaser == "") {
                            Fluttertoast.showToast(msg: "请填写全部信息");
                            return;
                          }
                          if (companyType == "2") if (taxpayer_id == "" ||
                              account == "" ||
                              bank == "") {
                            Fluttertoast.showToast(msg: "请填写全部信息");
                            return;
                          }
                          showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (_) {
                                return new NetLoadingDialog(
                                  loadingText: "添加中...",
                                  bgColor: Color.fromARGB(255, 0, 0, 0),
                                  requestCallBack: null,
                                  outsideDismiss: false,
                                );
                              });
                          register();
                        },
                      ),
                    )
                  ]))),
    );
  }

  del() async {
    Map map = new Map();
    map['token'] = token;
    map['invoice_id'] = widget.item.invoice_id;
    map['sign_type'] = createSignType(Api.URL_INVOICE_DEL);
    Response<String> response =
        await HttpUtil().post(Api.URL_INVOICE_DEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      Navigator.of(context).pop("1");
    }
  }

  register() async {
    if (widget.item != null) {
      Map map = new Map();
      map['token'] = token;
      map['invoice_id'] = widget.item.invoice_id;
      map['type'] = companyType == "2" ? "1" : "2";
      map['purchaser'] = purchaser;
      map['taxpayer_id'] = taxpayer_id;
      map['bank'] = bank;
      map['account'] = account;
      map['contact'] = contact;
      map['address'] = address;
      map['linkman'] = linkman;
      map['is_default'] = is_default;
      map['sign_type'] = createSignType(Api.URL_INVOICE_EDIT);
      Response<String> response =
          await HttpUtil().post(Api.URL_INVOICE_EDIT, data: getSign(map));
      Map userMap = json.decode(response.data);
      int code = userMap["code"];
      String msg = userMap["msg"];
      Fluttertoast.showToast(msg: msg);
      if (code == 1 && mounted) {
        Navigator.of(context).pop("1");
      }
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['type'] = companyType == "2" ? "1" : "2";
    map['purchaser'] = purchaser;
    map['taxpayer_id'] = taxpayer_id;
    map['bank'] = bank;
    map['account'] = account;
    map['contact'] = contact;
    map['address'] = address;
    map['linkman'] = linkman;
    map['is_default'] = is_default;
    map['sign_type'] = createSignType(Api.URL_INVOICE_ADD);
    Response<String> response =
        await HttpUtil().post(Api.URL_INVOICE_ADD, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      Navigator.of(context).pop("1");
    }
  }
}
